﻿using System;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using Solution.Business;
using Solution.Data;
using Solution.Utilities;
using Solution.Utilities.Security;
using Solution.Utilities.DynamicQueryable;
using Solution.Business.Infrastructure;
using System.Web;
using System.Web.Security;

namespace Solution.Mvc.Areas.Admin.Controllers
{
    [Authorize]
    public class SysUserCPController : Controller
    {
        //
        // GET: /Admin/UserCP/
        UserBLL Repository = new UserBLL();
        [CAuthorize(Module = "system", Functions = "V")]
        public ActionResult Index()
        {
            return View();
        }
        //
        public JsonResult GetData(bool? showBin, string sidx, string sord, int page, int rows)
        {
            bool _showBin = showBin ?? false;
            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = Repository.GetAll().Where(t => t.flag != "D").Where(p => p.Id != 1).Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
            var questions = Repository.GetAll().Where(t => t.flag != "D").Where(p => p.Id != 1).OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize).ToList();
            if (_showBin)
            {

                totalRecords = Repository.GetAll().Where(t => t.flag == "D").Where(p => p.Id != 1).Count();
                totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
                questions = Repository.GetAll().Where(t => t.flag == "D").Where(p => p.Id != 1).OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize).ToList();
            }
            var jsonData = new
            {
                total = totalPages,
                page,
                records = totalRecords,
                rows = (from question in questions
                        select new
                        {
                            i = question.Id.ToString(),
                            cell = new string[] { 
                                question.Id.ToString(), 
                                question.LoginName, 
                                question.FullName,
                                question.Email, 
                                question.Birthday.ToString(), 
                                question.LastLogin.ToString(), 
                                question.flag.ToString() 
                            }
                        }).ToArray()
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetUserByID(int myID)
        {
            User entity = Repository.Find(p => p.Id == myID).First<User>();
            var jsonData = new
            {

                Id = entity.Id,
                OpenId = entity.OpenId,
                Status = entity.Status,
                LoginName = entity.LoginName,
                Email = entity.Email,
                Avatar = entity.Avatar,
                Birthday = entity.Birthday,
                Sex = entity.Sex,
                FullName = entity.FullName,
                Password = entity.Password,
                Address = entity.Address,
                Phone = entity.Phone,
                Mobile = entity.Mobile,
                Yahoo = entity.Yahoo,
                Skype = entity.Skype,
                Facebook = entity.Facebook,
                Detail = entity.Detail,
                Skin = entity.Skin,
                LastLogin = entity.LastLogin,
                flag = entity.flag

            };


            return Json(jsonData, JsonRequestBehavior.AllowGet);

        }
        [CAuthorize(Module = "system", Functions = "I,U")]
        public JsonResult SubmitEditCreate(string oper, int? Id, string LoginName, string Email, string flag, string Sex, string FullName, string Password)
        {
            int ID = Id ?? 0;
            if (oper == "add")
            {
                User entity = new User();
                entity.LoginName = LoginName;//               ConvertUtility.ToString(collection["LoginName"]);
                entity.Email = Email;//           ConvertUtility.ToString(collection["Email"]);
                entity.flag = flag;//            ConvertUtility.ToString(collection["flag"]);
                entity.Sex = Sex;//         ConvertUtility.ToString(collection["Sex"]);
                entity.FullName = FullName;//              ConvertUtility.ToString(collection["FullName"]);
                entity.Password = Security.GetMd5Hash(Password);//              ConvertUtility.ToString(collection["Password"]);
                entity.Birthday = DateTime.Now;
                entity.LastLogin = DateTime.Now;
                if (Repository.Insert(entity))
                    return Json("ok", JsonRequestBehavior.AllowGet);
                else
                    return Json("err", JsonRequestBehavior.AllowGet);
            }
            else
            {
                try
                {
                    User myentity = Repository.GetOne(ID);
                    myentity.LoginName = LoginName;
                    myentity.Email = Email;
                    myentity.flag = flag;
                    myentity.Sex = Sex;
                    myentity.FullName = FullName;
                    if (Password.Length > 0)
                        myentity.Password = Security.GetMd5Hash(Password);
                    myentity.flag = "";
                    Repository.SaveChange();
                    return Json("ok", JsonRequestBehavior.AllowGet);
                }
                catch
                {
                    return Json("err", JsonRequestBehavior.AllowGet);

                }




            }
        }
        [CAuthorize(Module = "system", Functions = "I,D,U")]
        public JsonResult Edit(string oper, bool? delForever, string[] id, FormCollection collection)
        {



            //Chuỗi date1 thuộc định dạng "dd/MM/yyyy"
            String date1 = "14/03/2009";
            DateTime date = DateTime.ParseExact(date1, new string[] { "dd/MM/yyyy" }, CultureInfo.CurrentCulture, DateTimeStyles.AllowWhiteSpaces);
            string date2 = string.Format("{0: MM/dd/yyyy}", date);
            //Sẽ hiển thị ra chuỗi date2="03/14/2009";
            string[] ids = id;
            bool _delForever = delForever ?? false;
            // string oper = ConvertUtility.ToString(collection["oper"]);
            string Alias = ConvertUtility.ToString(collection["Alias"]);
            string DisplayName = ConvertUtility.ToString(collection["DisplayName"]);
            string Detail = ConvertUtility.ToString(collection["Detail"]);
            char flag = ConvertUtility.ToChar(collection["flag"]);

            switch (oper)
            {
                case "add": return Json("ok", JsonRequestBehavior.AllowGet);
                case "del":
                    bool _flag = true;
                    foreach (var item in ids)
                    {
                        int Id = ConvertUtility.ToInt(item);
                        User _entity = Repository.GetOne(Id);
                        if (_delForever)
                            Repository.Delete(_entity);
                        else
                        {
                            _entity.flag = "D";
                            if (!Repository.Update(_entity))
                                _flag = false;
                        }
                    }
                    if (_flag)
                        return Json("ok", JsonRequestBehavior.AllowGet);
                    return Json("err", JsonRequestBehavior.AllowGet);

                case "edit": return Json("ok", JsonRequestBehavior.AllowGet);

                default:
                    return Json("err", JsonRequestBehavior.AllowGet);
            }

        }
        //  {"rows":[{"id":"1","cell":["1","item 1","2.00","100.00","200.00"]},{"id":"2","cell":["2","item 2","3.00","50.00","150.00"]},{"id":"3","cell":["3","item 3","1.00","50.00","50.00"]},{"id":"4","cell":["4","item 4","1.00","200.00","200.00"]}]}

        public ActionResult Details(int id)
        {
            return View();
        }
        public JsonResult SaveTheme(string Css)
        {
            HttpCookie cookie = HttpContext.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
            UserData Ud = UserData.CreateUserData(ticket.UserData);
            Css = HttpUtility.UrlDecode(Css);
            User _User = Repository.GetOne(Ud.UserID);
            _User.Css = Css;
            if (Repository.Update(_User))
                return Json("ok", JsonRequestBehavior.AllowGet);
            return Json("err", JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetCusTheme()
        {
            User _user = Repository.GetOne(HttpContext.User.Identity.Name);
            if (_user != null)
                return Json("<style>" + _user.Css + "</style>", JsonRequestBehavior.AllowGet);
            return Json("<style></style>", JsonRequestBehavior.AllowGet);
        }

    }
}
